﻿using MyCommunity.Models;
using MyCommunity.DataAccess;
using System.Collections.Generic;
using MyCommunity.BusinessLogic;
using System;
using System.Security.Cryptography;
using System.Text;

public class UserService : IUserService
{
    private readonly IUserDAL userDAL;
    private readonly IEventDAL eventDAL;

    public UserService(IUserDAL userDAL)
    {
        this.userDAL = userDAL;
    }

    public List<User> GetAllUsers()
    {
        return this.userDAL.GetAllUsers();
    }

    public User getUser(String mail, String password)
    {

        User user = this.userDAL.GetUser(mail, password);

        return user;
    }

    public User getUser(String mail)
    {

        User user = this.userDAL.GetUser(mail);

        return user;
    }

    public List<User> FindUsers(String searchString)
    {

        if (!String.IsNullOrEmpty(searchString))
        {
            return this.userDAL.FindUsers(searchString);
        }

        // return this.userDAL.GetAllUsers();

        return CacheController.GetUser(this);
    }

    public User GetUser(int userId)
    {
        return this.userDAL.GetUser(userId);
    }

    public User CreateUser(UserRegisterModel userRegisterModel)
    {
        User user = this.userDAL.GetUser(userRegisterModel.Mail);

        if (user == null)
        {
            User newUser = new User();
            userRegisterModel.ApplyChanges(newUser);
            this.userDAL.Add(newUser);

            return newUser;
        }

        return null;
    }

    public void SaveChanges()
    {
        CacheController.deleteUserCache();
        this.userDAL.Save();
    }

    public static string MD5Hash(string value)
    {
        return Convert.ToBase64String(new MD5CryptoServiceProvider().ComputeHash(new UTF8Encoding().GetBytes(value)));
    }

    public static string GeneratePW(int Länge)
    {
        string ret = string.Empty;
        System.Text.StringBuilder SB = new System.Text.StringBuilder();
        string Content = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw!öäüÖÄÜß\"§$%&/()=?*#-";
        Random rnd = new Random();
        for (int i = 0; i < Länge; i++)
            SB.Append(Content[rnd.Next(Content.Length)]);
        return SB.ToString();
    }
}